package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.MqMessage;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.MqMessageService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> skuId1 = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId));
        if (skuId1 == null || skuId1.isEmpty()){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // 远程查询
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0){
                    wareSkuEntity.setSkuName(data.get("skuName").toString());
                }
            }catch (Exception e){

            }
            wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            // 查询库存
            Long count = baseMapper.getSkuStock(skuId);

            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean orderLockStock(WareSkuLockVo vo) {
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);

        // 找库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(item.getSkuId());
            skuWareHasStock.setNum(item.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIdList = wareSkuDao.listWareIdHasSkuStock(item.getSkuId());
            skuWareHasStock.setWareId(wareIdList);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        // 锁库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();

            if (CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException(skuId);
            }

            for (Long wareId:wareIds) {
                //锁定成功就返回1，失败就返回0   锁定库存，不是真实的减库存
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if (count == 1){
                    // 锁定成功 ， 真实减库存
                    skuStocked = true;
                    //

                    WareOrderTaskDetailEntity taskDetail = new WareOrderTaskDetailEntity();
                    taskDetail.setSkuId(skuId);
                    taskDetail.setSkuName("");
                    taskDetail.setTaskId(wareOrderTaskEntity.getId());
                    taskDetail.setWareId(wareId);
                    taskDetail.setLockStatus(1);
                    taskDetail.setSkuNum(hasStock.getNum());
                    wareOrderTaskDetailService.save(taskDetail);

                    // MQ 发消息锁定库存
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(wareOrderTaskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetail, stockDetailTo);
                    lockedTo.setDetail(stockDetailTo);
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    lockedTo.setMqMessageId(uuid);
                    CorrelationData correlationData = new CorrelationData(uuid);  //  给回调函数 使用

                    System.out.println("存入数据库 mq 日志。。。");
                    MqMessage mqMessage = new MqMessage();
                    mqMessage.setMessageId(uuid);
                    mqMessage.setMessageStatus(0);  // 新建
                    mqMessage.setContent(JSON.toJSONString(lockedTo));
                    mqMessage.setRoutingKey("order.create.order");
                    mqMessage.setToExchange("order-event-exchange");
                    mqMessage.setClassType(StockLockedTo.class.getTypeName());
                    mqMessage.setCreateTime(new Date());
                    mqMessage.setUpdateTime(new Date());
                    mqMessageService.save(mqMessage);

                    // 发送消息给库存交换机， 给延时队列， 说 我要锁定库存。
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockedTo, correlationData);


                    break;
                }
            }
            if (!skuStocked) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        //3、肯定全部都是锁定成功的
        return true;
    }

    @Override
    public void unLockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();

        /**
         * 解锁
         *      只解锁自己的库存业务相关的  锁定， 也就是库存订单任务表和库存订单任务详情表 。
         *      所以 要连个订单服务， 去查这个订单的具体状态。
         *      1、订单存在并且状态未取消
         *      2、订单不存在
         *      这两种都要 ，解锁
         */

        // 首选  先看自己库存 有没有加锁成功， 生成记录
        WareOrderTaskDetailEntity taskDetail = wareOrderTaskDetailService.getById(detailId);
        if (taskDetail != null) {
            // 查工作单 信息
            Long taskId = to.getId();
            WareOrderTaskEntity orderTask = wareOrderTaskService.getById(taskId);
            String orderSn = orderTask.getOrderSn();
            // todo  远程查看订单服务 找order  ， 看是否 订单成功
            R orderStatus = orderFeignService.getOrderStatus(orderSn);
            if (orderStatus.getCode() == 0) {
                // 成功
                OrderVo orderInfo = (OrderVo) orderStatus.getData("data", new TypeReference<OrderVo>() {
                });
                // 下面两种状态 都要解锁
                if (orderInfo == null ){  // 没有订单，说明下订单失败
                    if (taskDetail.getLockStatus() == 1) {  // 库存订单任务  状态为 已锁定 ， 才能解锁  。
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                }else if (orderInfo.getStatus() == 4){  // 已关闭
                    if (taskDetail.getLockStatus() == 1) {  // 库存订单任务  状态为 已锁定 ， 才能解锁  。
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                }

            }else {
                // 远程失败
                throw new RuntimeException("远程服务调用失败。");
            }
        }
    }

    @Transactional
    @Override
    public void unLockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        List<WareOrderTaskDetailEntity> taskDetailEntityList = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", orderTaskEntity.getId()).eq("lock_status",1));

        for (WareOrderTaskDetailEntity item : taskDetailEntityList) {
            unLockStock(item.getSkuId(),item.getWareId(), item.getSkuNum(), item.getId());
        }
    }

    private void unLockStock(Long skuId, Long wareId, Integer skuNum, Long detailId) {

        //库存解锁
        wareSkuDao.unLockStock(skuId,wareId,skuNum);

        // 更新工作单状态哦
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(detailId);
        wareOrderTaskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);

    }


    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}